package routes

import (
	v1 "gitee.com/buddyxiao/ginblog/api/v1"
	"gitee.com/buddyxiao/ginblog/middleware"
	"gitee.com/buddyxiao/ginblog/utils"
	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
	"net/http"
)

func createMyRender() multitemplate.Renderer {
	p := multitemplate.NewRenderer()
	p.AddFromFiles("admin", "static/admin/index.html")
	p.AddFromFiles("front", "static/front/index.html")
	return p
}
func InitRouter() {
	gin.ForceConsoleColor()
	gin.SetMode(utils.AppMode)
	r := gin.New()
	r.HTMLRender = createMyRender()
	r.Use(middleware.Logger())
	r.Use(gin.Recovery())
	r.Use(middleware.Cors())
	r.Static("/admin/static", "static/admin/static")
	r.Static("/static", "static/front/static")
	r.StaticFile("admin/favicon.ico", "static/admin/favicon.ico")
	r.StaticFile("/favicon.ico", "static/front/favicon.ico")
	r.GET("/admin", func(context *gin.Context) {
		context.HTML(http.StatusOK, "admin", nil)
	})
	r.GET("/", func(context *gin.Context) {
		context.HTML(http.StatusOK, "front", nil)
	})
	v1Path := "api/v1"
	auth := r.Group(v1Path)
	auth.Use(middleware.JwtToken())
	{
		// 用户模块的路由接口
		addUserRouter(auth)
		// 分类模块的路由接口
		addCategoryRouter(auth)
		// 文章模块的路由接口
		addArticleRouter(auth)
		// 上传文件
		auth.POST("upload", v1.Upload)
		// 更新用户信息设置
		auth.PUT("profile/:id", v1.UpdateProfile)
	}
	router := r.Group(v1Path)
	// 非授权模块
	noAuthRouter(router)
	r.Run(utils.HttpPort)
}

func noAuthRouter(router *gin.RouterGroup) {
	// 用户登录
	router.POST("login", v1.Login)
	// 查询多个用户
	router.GET("users", v1.GetUsers)
	// 查询某个用户
	router.GET("user/:id", v1.GetUserInfo)
	// 查询所有文章
	router.GET("articles", v1.GetArticles)
	// 查询单个文章
	router.GET("article/:id", v1.GetArticle)
	// 查询分类下的所有文章
	router.GET("articles/:id", v1.GetAllArticleOnCategory)
	// 查询分类
	router.GET("categories", v1.GetCategories)
	// 查询某个分类
	router.GET("category/:id", v1.GetCategory)
	// 获取用户信息设置
	router.GET("profile/:id", v1.GetProfile)

}

func addArticleRouter(router *gin.RouterGroup) {
	// 添加文章
	router.POST("article/add", v1.AddArticle)
	// 编辑文章
	router.PUT("article/:id", v1.EditArticle)
	// 删除文章
	router.DELETE("article/:id", v1.DeleteArticle)

}

func addCategoryRouter(router *gin.RouterGroup) {
	// 添加分类
	router.POST("category/add", v1.AddCategory)

	// 编辑分类
	router.PUT("category/:id", v1.EditCategory)
	// 删除分类
	router.DELETE("category/:id", v1.DeleteCategory)
}

func addUserRouter(router *gin.RouterGroup) {
	// 添加用户
	router.POST("user/add", v1.AddUser)

	// 编辑用户
	router.PUT("user/:id", v1.EditUser)
	// 删除用户
	router.DELETE("user/:id", v1.DeleteUser)
}
